package com.ejlchina.tool.fragment.viewpager

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentWeightCalibrationPagerBinding
import com.huyuhui.fastble.data.BleDevice
import com.ejlchina.tool.adapter.DeviceAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.enums.SuccessFailEnum
import com.ejlchina.tool.util.COMMAND_CURRENT_WEIGHT_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_CURRENT_WEIGHT_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_WEIGHT_CALIBRATION_DOWNWARD
import com.ejlchina.tool.util.COMMAND_WEIGHT_CALIBRATION_UPWARD
import com.ejlchina.tool.util.bytearray.intTo32HexStringLE
import com.ejlchina.tool.util.bytearray.intToByteHexString
import com.ejlchina.tool.util.bytearray.readByteArrayBE
import com.ejlchina.tool.util.bytearray.readInt32LE
import com.ejlchina.tool.view.GridItemDecoration
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.math.BigDecimal
import java.math.RoundingMode

class WeightCalibrationPagerFragment(val bleDeviceBean: BleDeviceBean) :
    BaseBindingFragment<FragmentWeightCalibrationPagerBinding>(FragmentWeightCalibrationPagerBinding::inflate) {

    private var calibrationStep = 0 //标记当前是第几部 ,0,1,2，其中0是默认初始值
    private var isCalibrationSuccess = false
    private var isCanStepTwo = false  //第一步是不是完成

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews() {
        initListeners()
    }

    private fun initListeners() {
        binding.tvBeginWeightSend.setOnClickListener {
            calibrationStep = 1
            setCalibrationWeight(bleDeviceBean, 0)
        }

        binding.btnConfirm.setOnClickListener {
            getCurrentWeight(bleDeviceBean)
        }

        binding.etCorrectWeight.doAfterTextChanged { editable ->
            editable?.let {
                val text = it.toString()
                setSendBtnState(binding.tvCorrectWeightSend, isCanStepTwo && text.isNotEmpty() && text.toInt() >= 10)
            }
        }

        binding.tvCorrectWeightSend.setOnClickListener {
            calibrationStep = 2
            setCalibrationWeight(bleDeviceBean, binding.etCorrectWeight.text.toString().toInt())
        }
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean, command: String, dataByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice, command, dataByteArray)
        dismissLoading()
        when (command) {
            COMMAND_WEIGHT_CALIBRATION_UPWARD -> {
                val showTextviewTip = if (calibrationStep == 1) binding.tvSendResult else binding.tvCorrectSendResult
                val weight = dataByteArray.readByteArrayBE(1, 4).readInt32LE().toString()
                val result = dataByteArray[0].toInt() == SuccessFailEnum.SUCCESS.value

                if (calibrationStep == 1) {
                    isCanStepTwo = true
                } else {
                    isCalibrationSuccess = result
                    binding.btnConfirm.visibility = View.VISIBLE
                }
                if (result) {
                    setResultTipState(showTextviewTip, isSuccess = true, shouldShow = true)
                    if (calibrationStep == 1) {
                        binding.etBeginWeight.setText(weight)
                        binding.etCorrectWeight.isEnabled = true
                    }
                } else {
                    setResultTipState(showTextviewTip, isSuccess = false, shouldShow = true)
                }
            }

            COMMAND_CURRENT_WEIGHT_GET_UPWARD -> {
                binding.btnConfirm.visibility = View.GONE
                val isStable = dataByteArray[dataByteArray.size - 1].toInt() == 1
                if (isStable) {
                    val number = (dataByteArray.readByteArrayBE(0, 4).readInt32LE() / 1000F).toDouble()
                    val num = BigDecimal(number)
                    val roundedNumber = num.setScale(2, RoundingMode.HALF_UP).toFloat()
                    if (roundedNumber <= 0){
                        setWeightCalibrationResult(false, 0F)
                        return
                    }
                    setWeightCalibrationResult(isCalibrationSuccess, roundedNumber)
                    setSendBtnState(binding.tvBeginWeightSend, false)
                    setSendBtnState(binding.tvCorrectWeightSend, false)
                } else {
                    setWeightCalibrationResult(false, 0F)
                }
            }
        }
    }

    private fun initData() {
    }

    @SuppressLint("SetTextI18n")
    private fun setWeightCalibrationResult(isSuccess: Boolean, weight: Float) {
        binding.layoutWeightCalibrationResult.visibility = View.VISIBLE
        binding.ivResult.setImageResource(if (isSuccess) R.drawable.icon_right_green else R.drawable.icon_error_red)
        binding.tvResult.text = if (isSuccess) "标定成功" else "标定失败：未检测到稳定重量"
        binding.tvResult.textSize = if (isSuccess) 26F else 18F
        binding.tvResultWeight.visibility = if (weight > 0) View.VISIBLE else View.GONE
        binding.tvResultWeight.text = weight.toString() + "KG"
        binding.btnConfirm.visibility = View.GONE
    }

    private fun setSendBtnState(viewId: TextView, viewIsEnable: Boolean) {
        val resID = if (viewIsEnable) R.drawable.shape_co_10_so_1f39ff else R.drawable.shape_co_10_so_d7d7d7
        viewId.apply {
            setBackgroundResource(resID)
            isEnabled = viewIsEnable
        }
    }

    private fun setResultTipState(viewId: TextView, isSuccess: Boolean, shouldShow: Boolean) {
        val textColor =
            if (isSuccess) resources.getColor(R.color.color_success_yellow, null) else resources.getColor(R.color.color_fail_red, null)
        viewId.setTextColor(textColor)
        viewId.visibility = if (shouldShow) View.VISIBLE else View.GONE
    }

    private fun setCalibrationWeight(bleDevice: BleDeviceBean, weight: Int) {
        val resultBuffer = intToByteHexString(1) + intTo32HexStringLE(weight * 1000)
        setCommandData(bleDevice, COMMAND_WEIGHT_CALIBRATION_DOWNWARD, resultBuffer)
    }

    private fun getCurrentWeight(bleDevice: BleDeviceBean) {
        getCommandData(bleDevice, COMMAND_CURRENT_WEIGHT_GET_DOWNWARD)
    }
}